<template>
  <el-drawer v-model="drawerProps.isView" :destroy-on-close="true" size="30%" :title="`${drawerProps.title}`">
    <el-form
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="!drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="用户信息" prop="name">
        <el-input v-model="user_id" placeholder="请填写用户id（不能重复）" clearable></el-input>
        <el-input v-model="password" placeholder="请填写密码" clearable></el-input>
        <el-input v-model="nick" placeholder="请填写昵称" clearable></el-input>
        <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup lang="ts" name="registerDrawer">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Bank } from "@/api/interface";
import { registerApi } from "@/api/modules/login";
import md5 from "md5";

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Bank.BankInfo>;
  api?: (params: any) => Promise<any>;
}
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

const user_id = ref<string>("");
const password = ref<string>("");
const nick = ref<string>("");
const rules = reactive({
  user_id: [{ required: true, message: "请填写用户名" }],
  password: [{ required: true, message: "请填写密码" }]
});
// 提交数据（新增/编辑）
const handleSubmit = async () => {
  if (user_id.value === "") {
    ElMessage.error({ message: `请填写用户id` });
    return;
  }
  if (password.value === "") {
    ElMessage.error({ message: `请填写用户密码` });
    return;
  }
  if (nick.value === "") {
    ElMessage.error({ message: `请填写用户昵称` });
    return;
  }
  try {
    const params = {
      user_id: user_id.value,
      password: md5(password.value),
      nick: nick.value
    };
    const data = await registerApi(params);
    if (data.code !== "") {
      ElMessage.error(data.msg);
      return;
    }
    ElMessage.success("注册成功");
    drawerProps.value.isView = false;
  } catch (error) {
    console.log(error);
  }
  return true;
};

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  drawerProps.value = params;
};

defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
@import "registerDrawer";
</style>
